<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>挑战大厂第3篇-new、call、create等常见函数的内部实现 | 前端一锅煮</title>
    <meta name="description" content="挑战大厂第3篇-new、call、create等常见函数的内部实现">
    <link rel="icon" href="/blog/logo.jpg">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="msapplication-TileColor" content="#000000">
    <meta name="keywords" content="挑战大厂第3篇-new、call、create等常见函数的内部实现">
    <link rel="preload" href="/blog/assets/css/0.styles.3a36f1f3.css" as="style"><link rel="preload" href="/blog/assets/js/app.2d50d9dc.js" as="script"><link rel="preload" href="/blog/assets/js/10.cf06b472.js" as="script"><link rel="prefetch" href="/blog/assets/js/11.57a175c6.js"><link rel="prefetch" href="/blog/assets/js/12.b32f2db2.js"><link rel="prefetch" href="/blog/assets/js/13.818a88b3.js"><link rel="prefetch" href="/blog/assets/js/14.1c54dd87.js"><link rel="prefetch" href="/blog/assets/js/15.40ea867f.js"><link rel="prefetch" href="/blog/assets/js/16.379721e3.js"><link rel="prefetch" href="/blog/assets/js/17.0b8bcd15.js"><link rel="prefetch" href="/blog/assets/js/18.41bb3889.js"><link rel="prefetch" href="/blog/assets/js/19.6362af40.js"><link rel="prefetch" href="/blog/assets/js/2.55dfcea5.js"><link rel="prefetch" href="/blog/assets/js/20.4ce40a8a.js"><link rel="prefetch" href="/blog/assets/js/21.ba4dcc65.js"><link rel="prefetch" href="/blog/assets/js/22.d2fad5dd.js"><link rel="prefetch" href="/blog/assets/js/23.2a976f6d.js"><link rel="prefetch" href="/blog/assets/js/24.a6407b77.js"><link rel="prefetch" href="/blog/assets/js/25.28818591.js"><link rel="prefetch" href="/blog/assets/js/26.a4d6759f.js"><link rel="prefetch" href="/blog/assets/js/27.fe72fdf4.js"><link rel="prefetch" href="/blog/assets/js/28.ca4a85a9.js"><link rel="prefetch" href="/blog/assets/js/29.4c6c0c28.js"><link rel="prefetch" href="/blog/assets/js/3.e235257b.js"><link rel="prefetch" href="/blog/assets/js/30.6aa9a972.js"><link rel="prefetch" href="/blog/assets/js/31.b7bccc14.js"><link rel="prefetch" href="/blog/assets/js/32.3544b6a6.js"><link rel="prefetch" href="/blog/assets/js/33.3bb697fd.js"><link rel="prefetch" href="/blog/assets/js/34.ac7cecf3.js"><link rel="prefetch" href="/blog/assets/js/35.b26fe96f.js"><link rel="prefetch" href="/blog/assets/js/36.91eb88f8.js"><link rel="prefetch" href="/blog/assets/js/37.baa3c248.js"><link rel="prefetch" href="/blog/assets/js/4.04108111.js"><link rel="prefetch" href="/blog/assets/js/5.2e3bc3e6.js"><link rel="prefetch" href="/blog/assets/js/6.88208dc4.js"><link rel="prefetch" href="/blog/assets/js/7.7913f494.js"><link rel="prefetch" href="/blog/assets/js/8.64ff3aa5.js"><link rel="prefetch" href="/blog/assets/js/9.43d70a25.js">
    <link rel="stylesheet" href="/blog/assets/css/0.styles.3a36f1f3.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/blog/" class="home-link router-link-active"><!----> <span class="site-name">前端一锅煮</span></a> <div class="links" style="max-width:nullpx;"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/blog/" class="nav-link">首页</a></div><div class="nav-item"><a href="/blog/page/list/" class="nav-link">全部文章</a></div><div class="nav-item"><a href="/blog/page/vuepress/" class="nav-link">VuePress笔记</a></div><div class="nav-item"><a href="/blog/page/about/" class="nav-link">关于我</a></div> <a href="https://gitee.com/cjm0/blog" target="_blank" rel="noopener noreferrer" class="repo-link">
    Gitee
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav></div></header> <div class="sidebar-mask"></div> <div class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/blog/" class="nav-link">首页</a></div><div class="nav-item"><a href="/blog/page/list/" class="nav-link">全部文章</a></div><div class="nav-item"><a href="/blog/page/vuepress/" class="nav-link">VuePress笔记</a></div><div class="nav-item"><a href="/blog/page/about/" class="nav-link">关于我</a></div> <a href="https://gitee.com/cjm0/blog" target="_blank" rel="noopener noreferrer" class="repo-link">
    Gitee
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav>  <ul class="sidebar-links"><li><div class="sidebar-group first"><p class="sidebar-heading open"><span>挑战大厂第3篇-new、call、create等常见函数的内部实现</span> <!----></p> <ul class="sidebar-group-items"><li><a href="/blog/page/challenge/fn.html#new" class="sidebar-link">new()</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/blog/page/challenge/fn.html#object-create" class="sidebar-link">Object.create()</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/blog/page/challenge/fn.html#instanceof" class="sidebar-link">instanceof</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/blog/page/challenge/fn.html#call" class="sidebar-link">call</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/blog/page/challenge/fn.html#apply" class="sidebar-link">apply</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/blog/page/challenge/fn.html#bind" class="sidebar-link">bind</a><ul class="sidebar-sub-headers"></ul></li></ul></div></li></ul> </div> <div class="page"> <div class="content"><h1 id="挑战大厂第3篇-new、call、create等常见函数的内部实现"><a href="#挑战大厂第3篇-new、call、create等常见函数的内部实现" class="header-anchor">#</a> 挑战大厂第3篇-new、call、create等常见函数的内部实现</h1> <blockquote><p>挑战大厂系列文章，转载请注明来源</p></blockquote> <p>解析 new()、Object.create()、instanceof、call()、apply()、bind()等6个方法函数的原理和内部实现</p> <h2 id="new"><a href="#new" class="header-anchor">#</a> new()</h2> <p>思路：把原型指向原型对象去获取方法，用 call/apply 去改 this 指向获取属性</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">function</span> <span class="token keyword">new</span><span class="token punctuation">(</span><span class="token parameter">fn<span class="token punctuation">,</span> <span class="token operator">...</span>args</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">/*
    原型：__proto__
    原型对象：prototype
    可用此方法替代：let obj = Object.create(fn.prototype)
  */</span>
  <span class="token comment">// 1. 创建一个空对象，将这个对象的原型指向构造函数的原型对象</span>
  <span class="token keyword">let</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span>
    __proto__<span class="token punctuation">:</span> fn<span class="token punctuation">.</span>prototype
  <span class="token punctuation">}</span>

  <span class="token comment">// 2. 执行构造函数，把里面的 this 指到这个对象</span>
  <span class="token keyword">let</span> res <span class="token operator">=</span> <span class="token function">fn</span><span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>obj<span class="token punctuation">,</span> args<span class="token punctuation">)</span>

  <span class="token comment">// 3. 返回值为 object 类型则作为 new 方法的返回值返回，否则返回这个空对象</span>
  <span class="token keyword">return</span> res <span class="token keyword">instanceof</span> <span class="token class-name">Object</span> <span class="token operator">?</span> res <span class="token punctuation">:</span> obj
<span class="token punctuation">}</span>
</code></pre></div><h2 id="object-create"><a href="#object-create" class="header-anchor">#</a> Object.create()</h2> <p>思路：创建一个空函数 F 作为中介去承接原型对象的方法，obj.<strong>proto</strong> = F.prototype = fn.prototype</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token comment">/*
  constructor 挂在原型对象 prototype 的属性上
  F.prototype = {
    constructor: F
  }

  把 fn.prototype 当做参数传进来
  F.prototype = proto
  F.prototype = fn.prototype = {
    constructor: fn
  }
  F.prototype = {
    constructor: fn
  }

  所以修改原型对象后需要重新把 constructor 指回去
*/</span>
<span class="token keyword">function</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token parameter">proto</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> <span class="token function-variable function">F</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
  <span class="token class-name">F</span><span class="token punctuation">.</span>prototype <span class="token operator">=</span> proto
  <span class="token class-name">F</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span>constructor <span class="token operator">=</span> <span class="token constant">F</span>
  <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">F</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><h2 id="instanceof"><a href="#instanceof" class="header-anchor">#</a> instanceof</h2> <p>思路：右边变量的原型对象存在于左边变量的原型链上</p> <p>原型链：obj.<strong>proto</strong>.<strong>proto</strong> 这样一直往上找直到 null 为止形成的链条</p> <div class="language-js extra-class"><pre class="language-js"><code>  <span class="token keyword">function</span> <span class="token function">myInstanceof</span><span class="token punctuation">(</span><span class="token parameter">left<span class="token punctuation">,</span> right</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">/*
      let proto = left.__proto__
      es6 新写法用 Object.getPrototypeOf(left) 替代 left.__proto__
    */</span>
    <span class="token keyword">let</span> proto <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">getPrototypeOf</span><span class="token punctuation">(</span>left<span class="token punctuation">)</span>

    <span class="token keyword">while</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>proto <span class="token operator">===</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">false</span>
      <span class="token punctuation">}</span>
      <span class="token comment">// 此时左边变量的原型等于右边变量的原型对象</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>proto <span class="token operator">===</span> right<span class="token punctuation">.</span>prototype<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span>
      <span class="token punctuation">}</span>
      <span class="token comment">// 不等于就继续往原型链上找，left.__proto__ = left.__proto__.__proto__</span>
      proto <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">getPrototypeof</span><span class="token punctuation">(</span>proto<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
</code></pre></div><h2 id="call"><a href="#call" class="header-anchor">#</a> call</h2> <p>思路：将要改变 this 指向的方法挂到目标 this 上执行并返回</p> <div class="language-js extra-class"><pre class="language-js"><code>  <span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">call</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">context <span class="token operator">=</span> window<span class="token punctuation">,</span> <span class="token operator">...</span>args</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">let</span> fn <span class="token operator">=</span> <span class="token function">Symbol</span><span class="token punctuation">(</span><span class="token string">'fn'</span><span class="token punctuation">)</span>
    context<span class="token punctuation">[</span>fn<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">this</span>
    <span class="token keyword">let</span> res <span class="token operator">=</span> context<span class="token punctuation">[</span>fn<span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span>
    <span class="token keyword">delete</span> context<span class="token punctuation">[</span>fn<span class="token punctuation">]</span>
    <span class="token keyword">return</span> res
  <span class="token punctuation">}</span>
</code></pre></div><p>解析：</p> <div class="language-js extra-class"><pre class="language-js"><code>  <span class="token comment">// 原理</span>
  <span class="token keyword">let</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span>
    name<span class="token punctuation">:</span> <span class="token string">'obj'</span><span class="token punctuation">,</span>
    <span class="token function-variable function">fn</span><span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>name<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
  obj<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 此时里面的 this 指向 obj</span>

  <span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">call</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span> <span class="token operator">...</span>args</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    obj <span class="token operator">=</span> <span class="token punctuation">{</span>
      fn<span class="token punctuation">:</span> f
    <span class="token punctuation">}</span>
    <span class="token keyword">let</span> res <span class="token operator">=</span> obj<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span>
    <span class="token keyword">delete</span> obj<span class="token punctuation">.</span>fn
    <span class="token keyword">return</span> res
  <span class="token punctuation">}</span>
  <span class="token function">f</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span>
</code></pre></div><h2 id="apply"><a href="#apply" class="header-anchor">#</a> apply</h2> <p>apply 和 call 是一样的，只是传的参数不一样，apply 传数组</p> <div class="language-js extra-class"><pre class="language-js"><code>  <span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">apply</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">context <span class="token operator">=</span> window<span class="token punctuation">,</span> arr</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">let</span> fn <span class="token operator">=</span> <span class="token function">Symbol</span><span class="token punctuation">(</span><span class="token string">'fn'</span><span class="token punctuation">)</span>
    context<span class="token punctuation">[</span>fn<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

    <span class="token keyword">let</span> res<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>arr<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      res <span class="token operator">=</span> context<span class="token punctuation">[</span>fn<span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
      res <span class="token operator">=</span> context<span class="token punctuation">[</span>fn<span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token operator">...</span>arr<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">delete</span> context<span class="token punctuation">[</span>fn<span class="token punctuation">]</span>
    <span class="token keyword">return</span> res<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
</code></pre></div><h2 id="bind"><a href="#bind" class="header-anchor">#</a> bind</h2> <p>思路：bind 利用 apply 来改变指针，Object.create 来克隆原方法的原型对象，最后返回一个新的函数</p> <div class="language-js extra-class"><pre class="language-js"><code>  <span class="token comment">/*
    1、可以指定this
    2、返回一个函数
    3、可以传入参数
    4、柯里化
    5、一个绑定函数也能使用new操作符创建对象：这种行为就像把原函数当成构造器，提供的 this 值被忽略，同时调用时的参数被提供给模拟函数
  */</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span>bind<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">bind</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">context<span class="token punctuation">,</span> <span class="token operator">...</span>args</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">let</span> fn <span class="token operator">=</span> <span class="token keyword">this</span>
      <span class="token keyword">let</span> <span class="token function-variable function">bound</span> <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 指定this</span>
        <span class="token keyword">return</span> <span class="token function">fn</span><span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>
          <span class="token keyword">this</span> <span class="token keyword">instanceof</span> <span class="token class-name">bound</span> <span class="token operator">?</span> <span class="token keyword">this</span> <span class="token punctuation">:</span> context<span class="token punctuation">,</span> <span class="token comment">// new 忽略</span>
          args<span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token operator">...</span>arguments<span class="token punctuation">)</span>
        <span class="token punctuation">)</span>
      <span class="token punctuation">}</span>
      bound<span class="token punctuation">.</span>prototype <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>prototype<span class="token punctuation">)</span>
      <span class="token keyword">return</span> bound
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
</code></pre></div></div> <div class="page-edit"><div class="edit-link"><a href="https://gitee.com/cjm0/blog/edit/master/docs/page/challenge/fn.md" target="_blank" rel="noopener noreferrer">在 Gitee 上编辑此页</a> <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></div> <!----></div> <!----> </div> <!----></div></div>
    <script src="/blog/assets/js/app.2d50d9dc.js" defer></script><script src="/blog/assets/js/10.cf06b472.js" defer></script>
  </body>
</html>
